﻿using System;
using System.Web;
using System.Web.DynamicData;
using System.Web.Routing;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.Expressions;
using PD.DataAccess;

namespace PD.Web.DynamicData.PageTemplates
{
    /// <summary>
    /// View all entities page.
    /// </summary>
    public partial class List : System.Web.UI.Page
    {
        /// <summary>
        /// The metadata that describes a table for use by Dynamic Data pages.
        /// </summary>
        private MetaTable table;

        /// <summary>
        /// Gets the table.
        /// </summary>
        public MetaTable Table
        {
            get { return this.table; }
        }

        /// <summary>
        /// Handles the Init event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Init(object sender, EventArgs e)
        {
            this.table = DynamicDataRouteHandler.GetRequestMetaTable(this.Context);
            this.GridView1.SetMetaTable(this.table, this.table.GetColumnValuesFromRoute(this.Context));
            this.GridDataSource.EntityTypeName = this.table.EntityType.AssemblyQualifiedName;
            if (this.table.EntityType != this.table.RootEntityType)
            {
                this.GridQueryExtender.Expressions.Add(new OfTypeExpression(this.table.EntityType));
            }
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = this.table.DisplayName;

            // Disable various options if the this.table is readonly
            if (this.table.IsReadOnly)
            {
                if (string.Compare(this.table.EntityType.FullName, typeof(Task).FullName, StringComparison.OrdinalIgnoreCase) != 0 &&
                    string.Compare(this.table.EntityType.FullName, typeof(Config).FullName, StringComparison.OrdinalIgnoreCase) != 0 &&
                    string.Compare(this.table.EntityType.FullName, typeof(Invoice).FullName, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    this.GridView1.Columns[0].Visible = false;
                }

                this.InsertHyperLink.Visible = false;
                this.GridView1.EnablePersistedSelection = false;
            }
        }

        /// <summary>
        /// Handles the RowDataBound event of the GridView1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DynamicHyperLink editLink = e.Row.FindControl("EditLink") as DynamicHyperLink;
                LinkButton deleteLink = e.Row.FindControl("DeleteLink") as LinkButton;
                if (this.table.EntityType.FullName == typeof(Task).FullName)
                {
                    Task task = e.Row.DataItem as Task;
                    editLink.Visible =
                        task.Status != TaskStatus.Approved &&
                        task.Status != TaskStatus.Rejected &&
                        task.AssignedTo == HttpContext.Current.ProviderUserKey().Value;
                }
                else if (this.table.EntityType.FullName == typeof(Invoice).FullName)
                {
                    Invoice invoice = e.Row.DataItem as Invoice;
                    editLink.Visible = deleteLink.Visible =
                        invoice.Status == InvoiceStatus.Incorrect ||
                        invoice.Status == InvoiceStatus.WaitingForCorrectInfo;
                }
            }
        }

        /// <summary>
        /// Handles the PreRender event of the Label control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Label_PreRender(object sender, EventArgs e)
        {
            Label label = (Label)sender;
            DynamicFilter dynamicFilter = (DynamicFilter)label.FindControl("DynamicFilter");
            QueryableFilterUserControl fuc = dynamicFilter.FilterTemplate as QueryableFilterUserControl;
            if (fuc != null && fuc.FilterControl != null)
            {
                label.AssociatedControlID = fuc.FilterControl.GetUniqueIDRelativeTo(label);
            }
        }

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Page.PreRenderComplete"/> event after the <see cref="M:System.Web.UI.Page.OnPreRenderComplete(System.EventArgs)"/> event and before the page is rendered.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
        protected override void OnPreRenderComplete(EventArgs e)
        {
            RouteValueDictionary routeValues = new RouteValueDictionary(this.GridView1.GetDefaultValues());
            this.InsertHyperLink.NavigateUrl = this.table.GetActionPath(PageAction.Insert, routeValues);
            base.OnPreRenderComplete(e);
        }

        /// <summary>
        /// Handles the FilterChanged event of the DynamicFilter control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void DynamicFilter_FilterChanged(object sender, EventArgs e)
        {
            this.GridView1.PageIndex = 0;
        }
    }
}
